import struct

def calculate_checksum(data):
    if len(data) % 2 != 0:
        data += b'\x00'  # 填充一个字节0以使数据长度为偶数
    
    checksum = 0
    for i in range(0, len(data), 2):
        word = (data[i] << 8) + data[i + 1]
        checksum += word
        # 处理进位
        checksum = (checksum & 0xffff) + (checksum >> 16)
    
    checksum = ~checksum & 0xffff  # 取反操作
    return checksum

def to_hex_string(data):
    return ' '.join(f'{byte:02x}' for byte in data)

# 给定的ICMP包
# icmp_packet = b'\x08\00\x4b\xe5\00\x01\x01\x76\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x61\x62\x63\x64\x65\x66\x67\x68\x69'
icmp_packet = b'\x08\00\x16\x14\x0b\xe9\x00\x11\xc3\xef\x6f\x66\x00\x00\x00\x00\xd6\xc8\x0d\x00\x00\x00\x00\x00\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37'
icmp_packet = b'\x00\00\x24\x26\x0b\xe9\x00\x11\xc3\xef\x6f\x66\x00\x00\x00\x00\xd6\xc8\x0d\x00\x00\x00\x00\x00\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37'

# 提取原始校验和
original_checksum = struct.unpack('!H', icmp_packet[2:4])[0]

# 将校验和字段设为0来计算新的校验和
icmp_packet_with_zero_checksum = icmp_packet[:2] + b'\x00\x00' + icmp_packet[4:]
calculated_checksum = calculate_checksum(icmp_packet_with_zero_checksum)

# 验证校验和是否正确
is_valid_checksum = original_checksum == calculated_checksum

hex_string = to_hex_string(icmp_packet)

print(f'原始校验和: {original_checksum:04x}')
print(f'计算得到的校验和: {calculated_checksum:04x}')
print(f'校验和是否有效: {is_valid_checksum}')
print(f'完整的ICMP数据包: {hex_string}')